import tkinter as tk
from tkinter import ttk
from enum import Enum
import threading
import time


class ScriptStatus(Enum):
    IDLE = "待机"
    RUNNING = "运行中"
    SUCCESS = "成功"
    FAILURE = "失败"


class FeatureClass:
    def __init__(self, master):
        self.master = master
        self.input_params = {}  # 输入参数字典
        self.components = []  # 组件列表
        self.buttons = []  # 按钮列表
        self.log_display = None  # 日志显示框
        self.status = ScriptStatus.IDLE  # 默认状态为待机

    def set_input_param(self, name, var):
        self.input_params[name] = var

    def get_input_param(self, name):
        return self.input_params.get(name, '')

    def set_components(self, components):
        self.components = components

    def set_buttons(self, buttons):
        self.buttons = buttons

    def set_log_display(self, log_display):
        self.log_display = log_display

    def run_feature(self):
        self.update_status(ScriptStatus.RUNNING)
        # 创建新线程执行确认动作
        thread = threading.Thread(target=self.execute_action)
        thread.start()

    def execute_action(self):
        # 子类需要实现的确认动作
        time.sleep(2)  # 模拟动作执行
        success = self.confirm_action()  # 子类方法，返回 True 或 False
        if success:
            self.update_status(ScriptStatus.SUCCESS)
        else:
            self.update_status(ScriptStatus.FAILURE)

    def confirm_action(self):
        raise NotImplementedError("Subclasses should implement confirm_action method.")

    def clear_inputs(self):
        for var in self.input_params.values():
            var.set("")  # 清空输入框内容
        self.update_status(ScriptStatus.IDLE)
        self.log("Inputs cleared.")

    def log(self, message):
        if self.log_display:
            self.log_display.insert(tk.END, f"{message}\n")
            self.log_display.see(tk.END)

    def create_panel(self, panel_frame):
        # 清空现有面板
        for widget in panel_frame.winfo_children():
            widget.destroy()

        # 创建面板组件
        for idx, component in enumerate(self.components):
            label_text = component.get('text', '')
            component_type = component.get('type', '')

            if component_type == 'label':
                label = ttk.Label(panel_frame, text=label_text)
                label.grid(row=idx, column=0, padx=5, pady=5, sticky="ew")

            elif component_type == 'entry':
                label_name = component.get('label_name', None)
                entry_name = component.get('name', '')
                if label_name is None:
                    label_name = entry_name
                label = ttk.Label(panel_frame, text=label_name)
                label.grid(row=idx, column=0, padx=5, pady=5, sticky='ew')
                var = tk.StringVar()
                entry = ttk.Entry(panel_frame, textvariable=var)
                entry.grid(row=idx, column=1, padx=5, pady=5, sticky='w')
                self.set_input_param(entry_name, var)

            elif component_type == 'combobox':
                label_name = component.get('label_name', None)
                combobox_name = component.get('name', '')
                if label_name is None:
                    label_name = combobox_name
                label = ttk.Label(panel_frame, text=label_name)
                label.grid(row=idx, column=0, padx=5, pady=5, sticky='ew')
                values = component.get('values', [])
                var = tk.StringVar()
                combobox = ttk.Combobox(panel_frame, values=values, textvariable=var)
                combobox.grid(row=idx, column=1,padx=5, pady=5, sticky='w')
                self.set_input_param(combobox_name, var)

        # 创建按钮
        button_frame = ttk.Frame(panel_frame)
        button_frame.grid(row=len(self.components), columnspan=2, pady=10)

        default_buttons = [
            {'label': '确认', 'command': self.run_feature},
            {'label': '清空输入', 'command': self.clear_inputs}
        ]
        for idx, button_info in enumerate(default_buttons):
            button_label = button_info.get('label', '')
            button_command = button_info.get('command', None)
            if button_command:
                button = ttk.Button(button_frame, text=button_label, command=button_command)
                button.grid(row=0, column=idx, padx=10)

        # 设置日志显示框到 FeatureClass
        self.set_log_display(self.log_display)

    def update_status(self, new_status):
        self.status = new_status
        self.master.update_status_label(self.status.value)


def get_feature_subclasses():
    feature_subclasses = []
    for cls in FeatureClass.__subclasses__():
        if issubclass(cls, FeatureClass):
            feature_subclasses.append(cls)
    return feature_subclasses
